<template>
  <view class="return-view">
    <view :style="{ height: capsuleInfo.top + 'px' }"></view>
    <image :style="{ height: capsuleInfo.height + 'px' }" src="/static/fanhui.png" mode="heightFix" @tap="back" />
  </view>
  <image class="goods-image" :src="goodsDetail?.image" mode="aspectFix" />
  <view class="product-Info">
    <text>{{ goodsDetail?.name }}</text>
    <text>{{ goodsDetail?.description }}</text>
  </view>
  <view class="specifications-view" v-for="(item, index) in goodsDetail?.attribute" :key="item._id">
    <text class="specification-title">{{ item.name }}</text>
    <view class="select-specifications">
      <button :class="{ selected: coname.includes(item2.name) }" :disabled="item2.disabled"
        @tap="selectSpec(index, item2)" v-for="item2 in item.subAttributes" :key="item2.sid">
        {{ item2.name }}
      </button>
    </view>
  </view>

  <view class="shopping-cart-area">
    <view class="select-goods price-padd">
      <view class="shopping-price">￥{{ attrCalculateInfo?.price }}</view>
      <view class="select-goods single-goods">
        <image v-show="(isReady || isSingleGoods) && goodsDetail?.quantity" @tap="handleQuantity(-1)"
          src="/static/jian-goods.png" mode="widthFix" />
        <text v-if="isReady || isSingleGoods">{{ goodsDetail?.quantity }}</text>
        <image v-if="isReady || isSingleGoods" @tap="handleQuantity(1)" src="/static/jia-goods.png" mode="widthFix" />
      </view>
    </view>
    <view class="selected-option">
      <text>{{ coname.replaceAll("-", "/") }}</text>
      <text>剩余库存：{{ attrCalculateInfo?.stock }}件</text>
    </view>
    <button class="cart_btn" v-show="(isReady || isSingleGoods) && goodsDetail?.quantity" @tap="addToCart">
      加入购物车
    </button>
  </view>
  <view style="height: 360rpx"></view>
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import request from "@/api/request";
import Decimal from "decimal.js";
import { useStore } from "@/store";
import type {
  AttrCalculateInfo,
  AttrDetail,
  GoodsInfo,
  SubAttributes,
  CartItem,
} from "@/types";
const capsuleInfo = uni.getStorageSync("capsule_btn");
const goodsDetail = ref<GoodsInfo>();
const attrList = ref<AttrDetail[]>([]);
const attrCalculateInfo = ref<AttrCalculateInfo>();
const store = useStore();
let dicsData: any = {};

onLoad(async (payload) => {
  const { data } = await request<GoodsInfo>("/getGoodsDetail", {
    _id: payload!._id,
  });
  goodsDetail.value = data;

  attrCalculateInfo.value = {
    price: data.price,
    stock: data.stock,
    name: new Array(data.attribute.length).fill(undefined),
  };
  const { data: atrData } = await request<AttrDetail[]>("/getAttrDetail", {
    _id: payload!._id,
  });
  const dics: string[] = [];
  const existDics = atrData
    .filter((item) => item.stock)
    .map((item) => ({
      [item.specs.join("-")]: {
        stock: item.stock,
        price: item.price,
        sids: item.sid,
        attrId: item._id,
      },
    }))
    .reduce((a, b) => ({ ...a, ...b }), {});
  console.log(existDics);

  data.attribute.forEach((item, index) => {
    const copySubs: string[] = JSON.parse(JSON.stringify(dics));

    item.subAttributes.forEach((sub) => {
      copySubs.forEach((item2) => {
        const coname = item2 + "-" + sub.name;
        sub.disabled = !Object.keys(existDics).find((item3) =>
          item3.includes(sub.name)
        );
        if (
          !sub.disabled &&
          item2.split("-").length !== data.attribute.length - 1
        ) {
          dics.push(coname);
        }
      });
    });
    dics.push(...item.subAttributes.map((item2) => item2.name));
  });

  dics.forEach((item) => {
    const filterDicKeys = Object.keys(existDics).filter((item2) =>
      item2.includes(item)
    );
    const stock = filterDicKeys.reduce((a, b) => a + existDics[b].stock, 0);

    dicsData[item] = { stock, price: 0, sid: [], attrId: "" };
  });
  Object.assign(dicsData, existDics);
  console.log(dicsData);

  attrList.value = atrData;
});
const isReady = computed(() => {
  return coname.value.split('-').length === goodsDetail.value?.attribute.length;
});
// index：当前选中的第几排属性
const selectSpec = (index: number, subAttributes: SubAttributes) => {
  // 设置选中项
  goodsDetail.value!.attribute[index].subAttributes.forEach(
    (item) => (item.selected = false)
  );
  subAttributes.selected = true;
  attrCalculateInfo.value!.name[index] = subAttributes.name;

  // 行数已满
  // 当前组合项不存在，保留当前项，移除其他项
  if (isReady.value) {
    if (!dicsData[coname.value]) {
      attrCalculateInfo.value!.name = attrCalculateInfo.value!.name.map((_item22, i) => i === index ? _item22 : undefined);
    }
  } else {
    // 行数未满，遍历其他未选中项，pass最后一项
    const indexes: number[] = [];
    attrCalculateInfo.value!.name.forEach((item, ins) => !item && indexes.push(ins));
    indexes.forEach(ii => {
      goodsDetail.value?.attribute[ii].subAttributes.forEach((item2) => {
        const copyName = JSON.parse(JSON.stringify(attrCalculateInfo.value!.name)) as string[];
        copyName[ii] = item2.name;
        const temname = copyName.filter(co => co).join("-");
        item2.disabled = !Boolean(dicsData[temname]);
      });
    });
  }
  console.log("计算名称", coname.value);

  attrCalculateInfo.value!.stock = dicsData[coname.value].stock;
  attrCalculateInfo.value!.price = dicsData[coname.value].price;
  handleQuantity(0);
};
const isSingleGoods = computed(() => goodsDetail.value?.attribute.length === 0);
const handleQuantity = (num: number) => {
  const quantify = goodsDetail.value!.quantity;
  goodsDetail.value!.quantity = quantify + num;
  attrCalculateInfo.value!.price = new Decimal(
    goodsDetail.value!.quantity
  ).times(new Decimal(isSingleGoods.value ? goodsDetail.value?.price : dicsData[coname.value].price));
};
const coname = computed(() => {
  return attrCalculateInfo.value?.name.filter((item) => item).join("-") || "";
});
const addToCart = () => {
  const params = {
    categoryId: goodsDetail.value!.categoryId,
    goodsId: goodsDetail.value!._id,
    name: goodsDetail.value!.name,
    image: goodsDetail.value!.image,
    price: isSingleGoods.value ? goodsDetail.value?.price : dicsData[coname.value].price,
    specs: isSingleGoods.value ? [] : attrCalculateInfo.value!.name as string[],
    sid: isSingleGoods.value ? [] : dicsData[coname.value].sids,
    quantity: goodsDetail.value!.quantity,
    attrId: isSingleGoods.value ? "" : dicsData[coname.value].attrId,
    totalPrice: attrCalculateInfo.value!.price,
  };
  store.addTocart(params);
  back();
  console.log(store.cartItems);
};
const back = () => {
  uni.navigateBack();
};
</script>
<style>
.selected {
  background-color: #214bd5 !important;
  color: #ffffff !important;
}

.return-view {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.return-view image {
  margin-left: 20rpx;
}

.goods-image {
  width: 100%;
  height: 550rpx;
}

.product-Info text {
  padding: 20rpx 20rpx 0 20rpx;
}

.product-Info text:nth-child(1) {
  font-size: 45rpx;
}

.product-Info text:nth-child(2) {
  font-size: 25rpx;
  line-height: 1.5;
}

/* 选择规格 */
.specifications-view {
  padding: 35rpx 20rpx 0 20rpx;
}

.specification-title {
  font-size: 28rpx;
  font-weight: bold;
  font-family: serif;
}

.select-specifications {
  display: flex;
  flex-wrap: wrap;
}

.select-specifications button {
  background-color: #ecf0f5;
  border-radius: 10rpx;
  padding: 10rpx 20rpx;
  font-size: 26rpx;
  margin: 20rpx 20rpx 0 0;
}

/* 底部购物车 */
.shopping-cart-area {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 68rpx;
  border-top: 1rpx solid #f5f5f5;
  background: #fff;
}

.price-padd {
  padding: 30rpx 20rpx;
}

.shopping-price {
  font-size: 40rpx;
  font-weight: bold;
}

.select-goods {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.single-goods image {
  width: 45rpx;
  height: 45rpx;
}

.single-goods text {
  font-size: 26rpx;
  padding: 0 27rpx;
}

.selected-option {
  display: flex;
  flex-wrap: wrap;
  padding: 0 20rpx;
  font-size: 25rpx;
  color: #979797;
}

.selected-option text {
  padding: 0 10rpx 10rpx 0;
}

.shopping-cart-area button {
  margin: 10rpx 20rpx;
  font-size: 30rpx;
  padding: 25rpx 0;
}

.cart_btn {
  background: #214bd5;
  color: #fff;
}
</style>
